<template>
  <div class="level-container">
    <div class="level-header">
      <button class="back-btn" @click="goBack">← 返回</button>
      <h2 class="level-title">{{ levelData.name }}</h2>
      <div class="progress">{{ currentQuestion + 1 }} / {{ questions.length }}</div>
    </div>

    <div class="level-content">
      <div class="question-area">
        <h3 class="question-text">找到数字 {{ currentQuestionData.target }}</h3>

        <div class="options-grid">
          <DraggableItem
            v-for="option in currentQuestionData.options"
            :key="option"
            :item-id="`number-${option}`"
            :item-value="option"
            item-type="number"
          >
            <div class="number-card">{{ option }}</div>
          </DraggableItem>
        </div>
      </div>

      <div class="answer-area">
        <DropZone
          ref="dropZoneRef"
          zone-id="answer"
          :accepted-value="currentQuestionData.target"
          accepted-type="number"
          :show-result="true"
          @drop="handleDrop"
        >
          <template #placeholder>
            <div class="drop-placeholder">
              <span class="drop-hint">把正确的数字拖到这里</span>
            </div>
          </template>
          <template #content="{ value }">
            <div class="dropped-number">{{ value }}</div>
          </template>
        </DropZone>
      </div>
    </div>

    <!-- 完成弹窗 -->
    <div v-if="showComplete" class="modal-overlay">
      <div class="modal-content complete-modal">
        <h2>🎉 太棒了！</h2>
        <div class="stars-earned">
          <span v-for="i in starsEarned" :key="i" class="star-big">⭐</span>
        </div>
        <p class="complete-message">你获得了 {{ starsEarned }} 颗星星！</p>
        <div class="complete-buttons">
          <button class="btn btn-primary" @click="goToMap">返回地图</button>
          <button v-if="hasNextLevel" class="btn btn-secondary" @click="goToNextLevel">
            下一关
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useGameStore } from '@/stores/game'
import DraggableItem from '@/components/common/DraggableItem.vue'
import DropZone from '@/components/common/DropZone.vue'
import { soundManager } from '@/utils/sound'
import { createStarEffect, createCelebrationEffect, injectAnimationStyles } from '@/utils/animation'

const router = useRouter()
const route = useRoute()
const gameStore = useGameStore()

const levelId = parseInt(route.params.id as string)
const levelData = computed(() => gameStore.levels.find(l => l.id === levelId)!)

const currentQuestion = ref(0)
const correctAnswers = ref(0)
const showComplete = ref(false)
const dropZoneRef = ref<InstanceType<typeof DropZone>>()

// 题目数据
const questions = ref([
  { target: 1, options: [1, 2, 3, 4] },
  { target: 3, options: [2, 3, 4, 5] },
  { target: 0, options: [0, 1, 2, 3] },
  { target: 5, options: [3, 4, 5, 6] },
  { target: 2, options: [1, 2, 3, 4] }
])

const currentQuestionData = computed(() => questions.value[currentQuestion.value])

const starsEarned = computed(() => {
  const accuracy = correctAnswers.value / questions.value.length
  if (accuracy >= 0.9) return 3
  if (accuracy >= 0.7) return 2
  return 1
})

const hasNextLevel = computed(() => {
  const nextLevel = gameStore.levels.find(l => l.id === levelId + 1)
  return nextLevel !== undefined
})

onMounted(() => {
  injectAnimationStyles()
  // 打乱选项
  questions.value.forEach(q => {
    q.options = shuffleArray(q.options)
  })
})

function shuffleArray<T>(array: T[]): T[] {
  const newArray = [...array]
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[newArray[i], newArray[j]] = [newArray[j], newArray[i]]
  }
  return newArray
}

function handleDrop(data: { correct: boolean }) {
  if (data.correct) {
    correctAnswers.value++

    // 创建星星特效
    const dropZone = dropZoneRef.value?.$el
    if (dropZone) {
      const rect = dropZone.getBoundingClientRect()
      createStarEffect(rect.left + rect.width / 2, rect.top + rect.height / 2)
    }

    // 延迟进入下一题
    setTimeout(() => {
      if (currentQuestion.value < questions.value.length - 1) {
        currentQuestion.value++
        dropZoneRef.value?.reset()
      } else {
        completeLevel()
      }
    }, 1500)
  } else {
    // 错误时重置
    setTimeout(() => {
      dropZoneRef.value?.reset()
    }, 1000)
  }
}

function completeLevel() {
  showComplete.value = true
  gameStore.completeLevel(levelId, starsEarned.value)
  createCelebrationEffect()
  soundManager.playBadge()
}

function goBack() {
  router.push('/')
}

function goToMap() {
  router.push('/')
}

function goToNextLevel() {
  router.push(`/level/${levelId + 1}`)
  // 重置当前关卡状态
  currentQuestion.value = 0
  correctAnswers.value = 0
  showComplete.value = false
}
</script>

<style scoped>
.level-container {
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 30px 20px;
  box-sizing: border-box;
  margin: 0;
}

.level-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40px;
  padding: 0 40px;
  width: 100%;
}

.back-btn {
  font-size: 20px;
  padding: 14px 28px;
  background: rgba(255, 255, 255, 0.95);
  border: none;
  border-radius: 50px;
  cursor: pointer;
  font-weight: 700;
  color: #667eea;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.back-btn:hover {
  background: #fff;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}

.level-title {
  font-size: 42px;
  font-weight: 800;
  color: #fff;
  margin: 0;
  text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
}

.progress {
  font-size: 22px;
  font-weight: 700;
  color: #fff;
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(10px);
  padding: 12px 28px;
  border-radius: 50px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.level-content {
  width: 100%;
  padding: 0 40px;
  box-sizing: border-box;
}

.question-area {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 30px;
  padding: 50px;
  margin-bottom: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.question-text {
  font-size: 52px;
  font-weight: 800;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0 0 50px 0;
}

.options-grid {
  display: flex;
  justify-content: center;
  gap: 40px;
  flex-wrap: wrap;
}

.number-card {
  width: 180px;
  height: 180px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 90px;
  font-weight: 800;
  color: #fff;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
  cursor: grab;
}

.number-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 35px rgba(102, 126, 234, 0.6);
}

.answer-area {
  display: flex;
  justify-content: center;
}

.drop-placeholder {
  padding: 40px;
}

.drop-hint {
  font-size: 24px;
  color: #999;
}

.dropped-number {
  font-size: 72px;
  font-weight: bold;
  color: #2196F3;
}

/* 完成弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.complete-modal {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 40px;
  padding: 70px;
  text-align: center;
  animation: scaleIn 0.5s ease;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  max-width: 600px;
}

@keyframes scaleIn {
  from {
    transform: scale(0.5);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

.complete-modal h2 {
  font-size: 56px;
  font-weight: 800;
  margin: 0 0 40px 0;
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.stars-earned {
  display: flex;
  justify-content: center;
  gap: 25px;
  margin-bottom: 40px;
}

.star-big {
  font-size: 80px;
  animation: starPop 0.6s ease-out;
  filter: drop-shadow(0 4px 8px rgba(255, 215, 0, 0.5));
}

@keyframes starPop {
  0% {
    transform: scale(0) rotate(0deg);
  }
  50% {
    transform: scale(1.3) rotate(180deg);
  }
  100% {
    transform: scale(1) rotate(360deg);
  }
}

.complete-message {
  font-size: 32px;
  font-weight: 700;
  color: #333;
  margin-bottom: 50px;
}

.complete-buttons {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.btn {
  padding: 18px 45px;
  font-size: 22px;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  font-weight: 700;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 25px rgba(0, 0, 0, 0.3);
}

.btn-primary {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: #fff;
}

.btn-secondary {
  background: linear-gradient(135deg, #FF9800 0%, #F57C00 100%);
  color: #fff;
}
</style>
